package spherical_tessellation_test;

import javax.vecmath.Point3f;
import javax.vecmath.Vector3f;

public class CoordinateVector extends Vector3f {

	private static final long serialVersionUID = -7464395599414365993L;

	private PlanetGeometry planet;
	private Point3f worldCoordinate;

	public CoordinateVector(float x, float y, float z, PlanetGeometry planet) {
		super(x, y, z);

		this.planet = planet;
		this.worldCoordinate = new Point3f();
	}

	public Point3f getWorldCoordinate() {
		Point3f planetCenter = planet.getCenter();
		worldCoordinate.setX(planetCenter.getX() + this.x);
		worldCoordinate.setY(planetCenter.getY() + this.y);
		worldCoordinate.setZ(planetCenter.getZ() + this.z);
		return worldCoordinate;
	}

	public CoordinateVector createMidpointVector(CoordinateVector other,
			boolean scaleRandom) {
		// Find midpoint
		float tempX, tempY, tempZ;
		tempX = this.x + other.getX();
		tempY = this.y + other.getY();
		tempZ = this.z + other.getZ();
		float length = this.getLength();
		CoordinateVector midpoint = new CoordinateVector(tempX / length, tempY
				/ length, tempZ / length, this.planet);

		// Scale vector length
		float maxScaleAmount = this.getWorldCoordinate().distance(
				other.getWorldCoordinate()) / 4.0f;
		float maxScaleFactor = 1.0f + (maxScaleAmount / this.getLength());
		float minScaleFactor = 1.0f - (maxScaleAmount / this.getLength());
		float scaleFactor = 1.0f;
		if (scaleRandom) {
			scaleFactor = minScaleFactor
					+ (int) (Math.random() * maxScaleFactor);
		} else {
			scaleFactor = maxScaleFactor;
		}
		midpoint.setX(midpoint.getX() * scaleFactor);
		midpoint.setY(midpoint.getY() * scaleFactor);
		midpoint.setZ(midpoint.getZ() * scaleFactor);

		return midpoint;
	}

	public float getLength() {
		return (float) Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2)
				+ Math.pow(z, 2));
	}

	public CoordinateVector getNormalizedVersion() {
		return new CoordinateVector(this.x / this.getLength(), this.y
				/ this.getLength(), this.z / this.getLength(), this.planet);
	}

}
